//
//  CategoryViewController.m
//  EveryDesigner
//
//  Created by CJX on 2016/10/31.
//  Copyright © 2016年 Shanghai DuRui Information Technology Company. All rights reserved.
//

#import "CategoryViewController.h"
#import "CategoryModel.h"
#import "CategoryBigCollectionViewCell.h"
#import "CommodityDetailsTableViewController.h"
#import "ProductListViewController.h"

#define SCROLLVIEWBUTTONWIDTH 100
#define CATEGORYBIGCELL @"bigCollectionCell"


@interface CategoryViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,CategoryBigCollectionViewCellDelegate>


@property(nonatomic,retain)NSMutableArray * scrollNameArray;

@property(nonatomic,retain)NSMutableArray * collectionArray;


@property(nonatomic,retain)UIScrollView * myScrollView;
@property(nonatomic,retain)UICollectionView * myCollection;
@property(nonatomic,retain)UIView * lineView;

@property(nonatomic,retain)NSMutableArray * buttonsArray;
@property(nonatomic,retain)UIButton * agoButton;
@property(nonatomic,retain)NSMutableArray * parmaArray;


@property(nonatomic,assign)NSInteger scrollTag;

@end

@implementation CategoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _scrollTag = 0;
    _scrollNameArray = [NSMutableArray arrayWithCapacity:0];
    _collectionArray = [NSMutableArray arrayWithCapacity:0];
    _buttonsArray = [NSMutableArray arrayWithCapacity:0];
    _parmaArray = [NSMutableArray arrayWithCapacity:0];

    
    [self creatNavView];
    [self getData];
    [self creatCollectionView];
}


-(void)creatNavView{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"CATEGORY";
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"nav_back"] forState:0];
    leftButton.frame=CGRectMake(0, 0, ACTUAL_WIDTH(23), ACTUAL_HEIGHT(23));
    [leftButton addTarget:self action:@selector(comeBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem*item=[[UIBarButtonItem alloc]initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem=item;
}

-(void)comeBack
{
    [[SlideNavigationController sharedInstance]popViewControllerAnimated:YES];
}


-(void)getData{
    NSString*urlStrr=[NSString stringWithFormat:@"%@",HTTP_ADDRESS];
    NSDictionary*paramss=@{@"main_page":@"category",
                           @"cPath":@"all"};
    HttpManager*managerr=[[HttpManager alloc]init];
    
    [managerr getDataFromNetworkWithUrl:urlStrr parameters:paramss compliation:^(id data, NSError *error) {
        NSLog(@"newLeftData>>>>>>%@",data);
        NSString*number=[NSString stringWithFormat:@"%@",data[@"status"]];
        
        if ([number isEqualToString:@"1"]) {
            NSArray * dataArr = data[@"data"];
            for (NSDictionary * dic in dataArr) {
                NSString * name = dic[@"categories_name"];
                [self.scrollNameArray addObject:name];
                
                NSString * parma = dic[@"param"];
                [self.parmaArray addObject:parma];
                
                NSMutableArray * smallArray = [[NSMutableArray alloc]init];
                NSArray * childArr = dic[@"child"];
                for (NSDictionary * dict in childArr) {
                    CategoryModel * model = [[CategoryModel alloc]initWithDictionay:dict];
                    [smallArray addObject:model];
                }
                [self.collectionArray addObject:smallArray];
            }
        }
        [self creatScrollView];
        
        [_myCollection reloadData];

    }];
}

-(void)creatScrollView{
    _myScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, KScreenWidth, KScreenHeight*0.05)];
    _myScrollView.backgroundColor = [UIColor whiteColor];
    _myScrollView.contentSize = CGSizeMake(_scrollNameArray.count*SCROLLVIEWBUTTONWIDTH, KScreenHeight*0.05);
    _myScrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_myScrollView];
    
    if (_scrollNameArray.count < 4) {
        for (int i = 0; i < _scrollNameArray.count; i++) {
            UIButton * scrollButton = [UIButton buttonWithType:UIButtonTypeCustom];
            scrollButton.frame = CGRectMake(KScreenWidth/_scrollNameArray.count*i, 3, KScreenWidth/_scrollNameArray.count, KScreenHeight*0.05-6);
            [scrollButton setTitle:_scrollNameArray[i] forState:UIControlStateNormal];
            [scrollButton setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
            [scrollButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [scrollButton addTarget:self action:@selector(scrollViewButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            scrollButton.tag = i;
            [_buttonsArray addObject:scrollButton];
            if (i == 0) {
                scrollButton.selected = YES;
                _agoButton = scrollButton;
            }else{
                scrollButton.selected = NO;
            }
            
            [_myScrollView addSubview:scrollButton];
        }
        
        _lineView = [[UIView alloc]initWithFrame:CGRectMake(0, KScreenHeight*0.05-2, KScreenWidth/_scrollNameArray.count, 2)];
        _lineView.backgroundColor = [UIColor redColor];
        [_myScrollView addSubview:_lineView];
    }else{
        for (int i = 0; i < _scrollNameArray.count; i++) {
            UIButton * scrollButton = [UIButton buttonWithType:UIButtonTypeCustom];
            scrollButton.frame = CGRectMake(SCROLLVIEWBUTTONWIDTH*i, 3, SCROLLVIEWBUTTONWIDTH, KScreenHeight*0.05-6);
            [scrollButton setTitle:_scrollNameArray[i] forState:UIControlStateNormal];
            [scrollButton setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
            [scrollButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [scrollButton addTarget:self action:@selector(scrollViewButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            scrollButton.tag = i;
            [_buttonsArray addObject:scrollButton];
            if (i == 0) {
                scrollButton.selected = YES;
                _agoButton = scrollButton;
            }else{
                scrollButton.selected = NO;
            }
            
            [_myScrollView addSubview:scrollButton];
        }
        
        _lineView = [[UIView alloc]initWithFrame:CGRectMake(0, KScreenHeight*0.05-2, SCROLLVIEWBUTTONWIDTH, 2)];
        _lineView.backgroundColor = [UIColor redColor];
        [_myScrollView addSubview:_lineView];
    }
    
    
}

-(void)scrollViewButtonClick:(UIButton *)button{
    _agoButton.selected = NO;
    button.selected = YES;
    _agoButton = button;
    _scrollTag = button.tag;
    

    if (_myScrollView.contentSize.width > KScreenWidth) {
        [self setupBtnCenter:button];
    }
    
    [_myCollection scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:button.tag inSection:0] atScrollPosition:UICollectionViewScrollPositionRight animated:YES];
    
    if(_scrollNameArray.count < 4){
        [UIView animateWithDuration:0.2 animations:^{
            
            _lineView.frame = CGRectMake( KScreenWidth/_scrollNameArray.count*button.tag, KScreenHeight*0.05-2, KScreenWidth/_scrollNameArray.count, 2);
        }];
    }else{
        [UIView animateWithDuration:0.2 animations:^{
            
            _lineView.frame = CGRectMake( SCROLLVIEWBUTTONWIDTH*button.tag, KScreenHeight*0.05-2, SCROLLVIEWBUTTONWIDTH, 2);
        }];
    }
    
    
    [_myCollection reloadData];
}

-(void)creatCollectionView{
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.sectionInset = UIEdgeInsetsZero;
    layout.itemSize = CGSizeMake(KScreenWidth, KScreenHeight*0.95-64);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    _myCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64+KScreenHeight*0.05, KScreenWidth, KScreenHeight*0.95-64) collectionViewLayout:layout];
    _myCollection.delegate = self;
    _myCollection.dataSource = self;
    _myCollection.pagingEnabled = YES;
    [self.view addSubview:_myCollection];
    _myCollection.showsHorizontalScrollIndicator = false;
    _myCollection.bounces = false;
    [_myCollection registerClass:[CategoryBigCollectionViewCell class] forCellWithReuseIdentifier:CATEGORYBIGCELL];
    
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _collectionArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CategoryBigCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CATEGORYBIGCELL forIndexPath:indexPath];

    cell.backgroundColor = [UIColor whiteColor];
    cell.dataArray = self.collectionArray[indexPath.item];
    cell.delegate = self;
    return cell;
}
-(void)letCategoryVCGoToCommodityVCWithId:(NSString *)ID andName:(NSString *)name andParma:(NSString *)parma{
    CommodityDetailsTableViewController * commodityVC = [[CommodityDetailsTableViewController alloc]init];
    commodityVC.idStr = ID;
    
    ProductListViewController * productVC = [[ProductListViewController alloc]init];
    productVC.ListOfSpeciesStr = @"products_list";
    productVC.cPathStr = ID ;
    productVC.categories_name = name;
    productVC.parmaStr = _parmaArray[_scrollTag];
    
    [self.navigationController pushViewController:productVC animated:YES];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView == _myCollection) {
        
        _scrollTag = scrollView.contentOffset.x/KScreenWidth;
        
        if(_scrollNameArray.count < 4){
            [UIView animateWithDuration:0.2 animations:^{
                
                _lineView.frame = CGRectMake( KScreenWidth/_scrollNameArray.count*_scrollTag, KScreenHeight*0.05-2, KScreenWidth/_scrollNameArray.count, 2);
            }];
        }else{
            [UIView animateWithDuration:0.2 animations:^{
                
                _lineView.frame = CGRectMake( SCROLLVIEWBUTTONWIDTH*_scrollTag, KScreenHeight*0.05-2, SCROLLVIEWBUTTONWIDTH, 2);
            }];
        }
        
        _agoButton.selected = NO;
        UIButton * button = _buttonsArray[_scrollTag];
        button.selected = YES;
        _agoButton = button;
        
        if (_myScrollView.contentSize.width > KScreenWidth) {
            [self setupBtnCenter:button];
        }
    }
    
    [_myCollection reloadData];
}

-(void)setupBtnCenter:(UIButton *)button{
    
    CGFloat offsetX = button.center.x - KScreenWidth/2;
    if (offsetX < 0) {
        offsetX = 0;
    }
    CGFloat maxOffsetX = SCROLLVIEWBUTTONWIDTH*self.scrollNameArray.count-KScreenWidth;
    
    if (offsetX>maxOffsetX) {
        offsetX = maxOffsetX;
    }
    
    _myScrollView.contentOffset = CGPointMake(offsetX, 0);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
